﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using BELLTruongThinh.Models;

namespace BELLTruongThinh.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        private TruongThinhEntities db = new TruongThinhEntities();

        public ActionResult Register(string username,string email,string password, string repassword, string phone, string address)
        {
            try
            {
                if (password == repassword)
                {
                    User u = new User();
                    u.Role = 3;
                    u.Username = username;
                    u.Email = email;
                    u.Password = password;
                    u.Phone = phone;
                    u.Address = address;
                    u.Fullname = "sgsjf";
                    db.Users.Add(u);
                    db.SaveChanges();
                    Session["nosucess"] = "<script language=javascript>alert('Đăng ký thành công');</script>";
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    Session["nosucess"] = "<script language=javascript>alert('Đăng ký bị lỗi, vui lòng kiểm tra lại');</script>";
                    return RedirectToAction("Index", "Home");
                }
            }
            catch
            {
                return Redirect("Error.cshtml");
            }
        }
        public ActionResult Login(string Email, string pass)
        {
            User u = db.Users.Where(m => m.Email == Email && m.Password == pass).FirstOrDefault();
            if (u == null)
            {
                Session["errorlogin"] = "<script language=javascript>alert('Email hoặc mật khẩu không đúng');</script>";
                return RedirectToAction("Index", "Home");
            }
            else
            {
                Session["user"] = u.Username;
                //FormsAuthentication.SetAuthCookie(u.Role, true);
                //if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                //        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                //{
                //    return Redirect(returnUrl);
                //}
                //else
                //{
                //    return RedirectToAction("Index", "Home");
                //}
                return RedirectToAction("Index", "Home");
            }
        }
        public ActionResult LogOff()
        {
            Session["user"] = null;
            return RedirectToAction("Index", "Home");
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
